<%#
 Copyright 2013-2020 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
<?xml version="1.0" encoding="utf-8"?>
<databaseChangeLog
    xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
    xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-<%= LIQUIBASE_DTD_VERSION %>.xsd
                        http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <% let autoIncrementValue = entity.primaryKeyType !== 'String';
        let databasePKType = entity.primaryKeyType !== 'String' ? 'bigint' : 'varchar(100)';
        const isAutoIncrementDB = reactive || ['mysql', 'mariadb'].includes(prodDatabaseType);
    _%>
    <%_ if (isAutoIncrementDB) { _%>
    <property name="autoIncrement" value="<%- autoIncrementValue %>"/>
    <%_ } _%>

    <!--
        Added the entity <%= entity.entityClass %>.
    -->
    <changeSet id="<%= changelogDate %>-1" author="jhipster">
        <createTable tableName="<%= entity.entityTableName %>"<%- formatAsLiquibaseRemarks(entity.javadoc, true) %>>
            <column name="id" type="<%= databasePKType %>" <%_ if (entity.primaryKeyType === 'String' ) { _%> <% } else if (isAutoIncrementDB) { %> autoIncrement="${autoIncrement}" <%_ } %>>
                <constraints primaryKey="true" nullable="false"/>
            </column>
            <%_ for (idx in fields) {
                const nullable = fields[idx].nullable;
                const fieldType = fields[idx].fieldType;
                const fieldTypeBlobContent = fields[idx].fieldTypeBlobContent;
                const columnName = fields[idx].fieldNameAsDatabaseColumn;
                const columnType = fields[idx].columnType;
                _%>
            <column name="<%= columnName %>" type="<%= columnType %>"<%- formatAsLiquibaseRemarks(fields[idx].javadoc, true) %>>
                <%_ if (fields[idx].unique) { _%>
                <constraints nullable="<%= nullable %>" unique="true" uniqueConstraintName="<%= fields[idx].uniqueConstraintName %>" />
                <%_ } else { _%>
                <constraints nullable="<%= nullable %>" />
                <%_ } _%>
            </column>
                <%_ if (fieldType === 'byte[]' && fieldTypeBlobContent !== 'text') {
                    let contentTypeColumnType = columnType;
                    contentTypeColumnType = "varchar(255)"; _%>
            <column name="<%= columnName %>_content_type" type="<%= contentTypeColumnType %>">
                <constraints nullable="<%= nullable %>" />
            </column>
                <%_ }
            } _%>
            <%_ for (idx in relationships) {
                let nullable_relation = true,
                relationshipType = relationships[idx].relationshipType,
                relationshipName = relationships[idx].relationshipName,
                relationshipColumnType = relationships[idx].otherEntityPrimaryKeyType === 'String' ? 'varchar(100)' : 'bigint';
                if (relationships[idx].relationshipValidate === true && relationships[idx].relationshipRequired) {
                    nullable_relation = false;
                }
                if (relationships[idx].relationshipType === 'many-to-one') { _%>
            <column name="<%= relationships[idx].columnName %>_id" type="<%= relationshipColumnType %>">
                <constraints nullable="<%= relationships[idx].nullable %>" />
            </column>
            <%_ } else if (relationshipType === 'one-to-one' && relationships[idx].ownerSide === true
                            && (relationships[idx].useJPADerivedIdentifier == null || relationships[idx].useJPADerivedIdentifier === false)) {
                const uniqueConstraintName = getUXConstraintName(entity.entityTableName, relationships[idx].columnName + '_id', entity.prodDatabaseType);
            _%>
            <column name="<%= relationships[idx].columnName %>_id" type="<%= relationshipColumnType %>">
                <constraints unique="true" nullable="<%= relationships[idx].nullable %>" uniqueConstraintName="<%= uniqueConstraintName %>" />
            </column>
            <%_ }
            } _%>
            <!-- jhipster-needle-liquibase-add-column - JHipster will add columns here -->
        </createTable>
        <%_ for (const idx in fields) {
            if (fields[idx].shouldDropDefaultValue) { _%>
        <dropDefaultValue tableName="<%= entity.entityTableName %>" columnName="<%= fields[idx].columnName %>" columnDataType="${datetimeType}"/>
        <%_ }
        } _%>
    </changeSet>

    <changeSet id="<%= changelogDate %>-1-relations" author="jhipster">
        <%_ for (idx in relationships) {
            const relationshipType = relationships[idx].relationshipType,
            relationshipName = relationships[idx].relationshipName,
            ownerSide = relationships[idx].ownerSide,
            otherEntityName = relationships[idx].otherEntityName;
            const relationshipColumnType = relationships[idx].otherEntityPrimaryKeyType === 'String' ? 'varchar(100)' : 'bigint';
            if (relationshipType === 'many-to-many' && ownerSide) {
                const joinTableName = getJoinTableName(entity.entityTableName, relationshipName, prodDatabaseType);
          _%>

        <createTable tableName="<%= joinTableName %>">
            <column name="<%= relationships[idx].columnName %>_id" type="<%= relationshipColumnType %>">
                <constraints nullable="false"/>
            </column>
            <column name="<%= getColumnName(entity.name) %>_id" type="bigint">
                <constraints nullable="false"/>
            </column>
        </createTable>

        <addPrimaryKey columnNames="<%= getColumnName(entity.name) %>_id, <%= relationships[idx].columnName %>_id" tableName="<%= joinTableName %>"/>
        <% } %><% } %>
    </changeSet>
    <!-- jhipster-needle-liquibase-add-changeset - JHipster will add changesets here -->
    <%_ if (!skipFakeData) { _%>

    <!--
        Load sample data generated with Faker.js
        - This data can be easily edited using a CSV editor (or even MS Excel) and
          is located in the 'src/main/resources/config/liquibase/fake-data' directory
        - By default this data is applied when running with the JHipster 'dev' profile.
          This can be customized by adding or removing 'faker' in the 'spring.liquibase.contexts'
          Spring Boot configuration key.
    -->
    <changeSet id="<%= changelogDate %>-1-data" author="jhipster" context="faker">
        <loadData
                  file="config/liquibase/fake-data/<%= !entity.incrementalChangelog ? entity.entityTableName : databaseChangelog.changelogDate + '_entity_' + entity.entityClass %>.csv"
                  separator=";"
                  tableName="<%= entity.entityTableName %>">
            <column name="id" type="numeric"/>
            <%_ for (idx in fields) {
                _%>
            <column name="<%= fields[idx].columnName %>" type="<%= fields[idx].loadColumnType %>"/>
                <%_ if (fields[idx].fieldType === 'byte[]' && fields[idx].fieldTypeBlobContent !== 'text') { _%>
            <column name="<%= fields[idx].columnName %>_content_type" type="string"/>
                <%_ } _%>
            <%_ } _%>
            <%_ for (idx in relationships) {
                    let loadColumnType = relationships[idx].otherEntityPrimaryKeyType === 'String' ? 'string' : 'numeric';
                    if (relationships[idx].relationshipValidate === true && relationships[idx].relationshipRequired
                        && (relationships[idx].relationshipType === "many-to-one"
                            || (relationships[idx].relationshipType === "one-to-one" && relationships[idx].ownerSide === true
                                && (relationships[idx].useJPADerivedIdentifier == null || relationships[idx].useJPADerivedIdentifier === false))
                    )) {
                        let baseColumnName = relationships[idx].columnName + '_id';
                        _%>
            <column name="<%= baseColumnName %>" type="<%= loadColumnType %>"/>
                    <%_ } _%>
            <%_  } _%>
            <!-- jhipster-needle-liquibase-add-loadcolumn - JHipster (and/or extensions) can add load columns here -->
        </loadData>
    </changeSet>
    <%_ } _%>

</databaseChangeLog>
